#!/bin/sh /etc/rc.common
START=60
. /lib/config/uci.sh
uci_load openvpn

status="0"
file_check() {
	for file in "$@"; do
		if [ ! -f "$file" ]; then
			logger "$0: Missing $file. Please generate and try again."
			status="1"
		fi
	done
}

start() {
	case "$CONFIG_general_mode" in
		client)
			SERVER="$CONFIG_client_ipaddr"
			PROTO="$CONFIG_general_proto"
			PORT="$CONFIG_general_port"
	
			[ "$SERVER" ] || {
				logger "$0: remote server not configured!"
				exit
			}

			[ "$SERVER" ] && {
				SERVER_OPTION="--remote $SERVER --nobind"
			}

			case "$CONFIG_client_auth" in
				cert)
					file_check "/etc/openvpn/certificate.p12"
					AUTH_OPTION="--client --pkcs12 /etc/openvpn/certificate.p12"
				;;
				psk)
					file_check "/etc/openvpn/shared.key"
					AUTH_OPTION="--secret /etc/openvpn/shared.key"
				;;
				pem)
					file_check "/etc/openvpn/ca.crt" "/etc/openvpn/client.crt" "/etc/openvpn/client.key"
					AUTH_OPTION="--client --ca /etc/openvpn/ca.crt --cert /etc/openvpn/client.crt --key /etc/openvpn/client.key"
				;;
				*)
					logger "$0: unknown authentication type, aborting!"
					exit
				;;
			esac

			if [ "$status" = "0" ]; then
			openvpn --proto  "${PROTO:-udp}"		\
				--port   "${PORT:-1194}"		\
				$SERVER_OPTION				\
				--dev tun				\
				$AUTH_OPTION				\
				--comp-lzo				\
				--daemon				\
				--status /tmp/openvpn-status.log	\
				--verb 3
			fi
		;;
		server)
			echo "Not yet implimented"
			exit 0
		;;
		*)
			exit 0
		:;
	esac	
}
restart() {
		$0 stop
		sleep 3
		$0 start
}
reload() {
		killall -SIGHUP openvpn
}
stop() {
		killall openvpn
}